// pages/login/login.js
const app = getApp()
const utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAgree:true,
    disabled:false,
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showModal: false,//定义登录弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  //是否同意协议
  isAgress:function (){
    let isAgress = this.data.isAgree;
    if (isAgress) {
      this.setData({
        isAgree:false,
        disabled:true
      })
    }else{
      this.setData({
        isAgree:true,
        disabled:false
      })
    }
  },
  bindGetUserInfo: function (e) {//点击的“拒绝”或者“允许
    if (e.detail.userInfo) {//点击了“允许”按钮，
      var that = this;
      console.log(e.detail.userInfo)
      var sex;
      if (e.detail.userInfo.gender == 1) {
        sex = 0
      }else{
        sex = 1
      }
      // console.log(e.detail.userInfo.avatarUrl);
      wx.setStorageSync('faceUrl', e.detail.userInfo.avatarUrl)
      this.setData({
        avatarUrl:e.detail.userInfo.avatarUrl,
        nickName:e.detail.userInfo.nickName,
        sex:sex
      })
      this.wxlogin()
    } else {
      wx.navigateBack({
        delta:1
      })
    }
  },
  noLogin:function () {
    wx.navigateBack({
      delta:1
    })
  },
  // 显示一键获取手机号弹窗
  showDialogBtn: function () {
    this.setData({
      showModal: true//修改弹窗状态为true，即显示
    })
  },
  // 隐藏一键获取手机号弹窗
  hideModal: function () {
    this.setData({
      showModal: false//修改弹窗状态为false,即隐藏
    });
  },
  //绑定手机
  getPhoneNumber: function (e) {
    var that = this;
    wx.checkSession({
      success: function () {
        that.hideModal();

        var ency = e.detail.encryptedData;
        var iv = e.detail.iv;
        var sessionk = that.data.sessionKey;

        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
          that.showDialogBtn()
        }else{//同意获取手机号
          that.hideModal();
          utils.requestUrl({//将用户信息传给后台数据库
            // method:'post',
            url: "/niu/apiv3/member_login_phone_wxcrypt.php",
            params: {
              unid: wx.getStorageSync('unionId'),
              session_key:sessionk,
              encryptedData:ency,
              iv:iv,
              openid1:wx.getStorageSync('openId'),
              openid2:'',
              nan:that.data.sex,
              faceurl:that.data.avatarUrl,
              nick:that.data.nickName
            }
          }).then((res) => {
            // var data = res;
            console.log(res);
            if (res.data.resultcode == 0) {
              wx.setStorageSync('markId', res.data.markid);
              wx.setStorageSync('userId',res.data.id)
              app.IMInit();
              wx.navigateBack({
                delta:1
              })
            }else{
              utils.toast(res.data.msg)
            }
          })
        }
      },
      fail: function () {
        console.log("session_key 已经失效，需要重新执行登录流程");
        that.wxlogin(); //重新登录
      }
    })
  },
  
wxlogin: function () {
  var that = this;
  wx.login({
    success: (res) => {
      console.log(res)
      utils.requestUrl({
        // method:'post',
        url: "/niu/apiv3/member_login_wxscode2info.php",
        params: {
          code: res.code,
        }
      }).then((res) => {
        console.log(res);
        if (res.data.resultcode == 0){

          var data = res.data.data;
          // 存储用户信息
          this.setData({
            sessionKey:data.session_key
          })
          wx.setStorageSync('markId', data.markid) 
          wx.setStorageSync('userId', data.userid)
          wx.setStorageSync('unionId', data.unionid)
          wx.setStorageSync('openId', data.openid)
          
          if (data.hadinfo == 0) {
            that.showDialogBtn();//调用一键获取手机号弹窗（自己写的）
          }else{
            app.IMInit();
            wx.navigateBack({
              delta:1
            })
          }

        }else{

          var sessionKey = res.data.data.session_key
          this.setData({
            sessionKey:sessionKey
          })

          wx.setStorageSync('openId', res.data.data.openid);
          wx.getUserInfo({
            success: function(res) {
              console.log(res);
              var encryptedData = res.encryptedData;
              var iv = res.iv
              utils.requestUrl({
                url:'/niu/apiv3/member_weixincrypt.php',
                params: {
                  session_key:sessionKey,
                  encryptedData:encryptedData,
                  iv:iv
                }
              }).then((res) =>{
                console.log(res);
                wx.setStorageSync('unionId', res.data.data.unionId);
                that.showDialogBtn();//调用一键获取手机号弹窗（自己写的）
              })
            }
          })

          
        }
      })
    }
  });

},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})